<?php
namespace Home\Controller;
use Home\Controller\TradeFatherController;
use Common\Logic\TradeLogic;
class TradeController extends OrdersController {
	protected  $currency;
	protected  $entrust;
	protected  $trade;
	public function _initialize(){
		parent::_initialize();

		$this->currency=M('Currency');
		$this->entrust=M('Entrust');
		$this->trade=M('Orders');
	}
	//空操作
	public function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('Public:404');
	}
	
    
    //买入
     public function buy($l=1){
    	/* if(!empty($p)){
    		$_POST=$p;
    	} */
    	$token=I('token');
		$where1['token']=$token;
		$member_id=M('token')->where($where1)->find()['uid'];
		
		$currency_id=I('currency_id');
		
		$buyprice=floatval(I('buyprice'));
		$buynum=floatval(I('buynum'));
		$buypwd=I('buypwd');
        if(!$member_id){
            $data['status']=0;
            $data['info']='请先登录再进行此操作';
            $this->ajaxReturn($data,'JSONP');
        }
        $member=M('Member')->where('member_id='.$member_id)->find();
        if($member['status']!=3){
        	$data['status']=0;
        	$data['info']='您的账户未审核，不能进行交易';
        	$this->ajaxReturn($data,'JSONP');
        }
        $currency=$this->getCurrencyByCurrencyId($currency_id);
		$time=strtotime(date('Y-m-d'));
		$start_time=$time+$currency['start_time_h']*3600+$currency['start_time_m']*60;
		$over_time=$time+$currency['end_time_h']*3600+$currency['end_time_m']*60;
		$start_x_time=$time+$currency['start_time_x_h']*3600+$currency['start_time_x_m']*60;
		$over_x_time=$time+$currency['end_time_x_h']*3600+$currency['end_time_x_m']*60;
		
		if($member_id!=184){
		if((time()<$start_time||time()>$over_time)  &&  (time()<$start_x_time||time()>$over_x_time)){
			$data['status']=-101;
			$data['info']='交易未开启，请在交易时间内进行交易。';
			$this->ajaxReturn($data,'JSONP');
		}
		$week = date("l",time());  //获取当前日期是周几
		if($week == 'Saturday' && $currency['is_lock_6'] == 1){
			$data['status']=-10;
			$data['info']='交易未开启，请在交易时间内进行交易。';
			$this->ajaxReturn($data,'JSONP');
		}
		if($week == 'Sunday' && $currency['is_lock_7'] == 1 ){
			$data['status']=-10;
			$data['info']='交易未开启，请在交易时间内进行交易。';
			$this->ajaxReturn($data,'JSONP');
		}
	}
        //获取币的相关信息
      // $currency=$this->getCurrencyByCurrencyId($buycurrency_id);
        if ($currency['is_lock']){
            $data['status']=-5;
            $data['info']= '该币种暂时不允许交易';
            $this->ajaxReturn($data,'JSONP');
        }
//         if(!is_numeric($buyprice)||!is_numeric($buynum)){
//             $data['status']=0;
//             $data['info']='您的挂单价格或数量有误,请修改';
//             $this->ajaxReturn($data);
//         }
        if($buyprice<0){
        	$data['status']=-12;
        	$data['info']='您的挂单价格请输入正数';
        	$this->ajaxReturn($data,'JSONP');
        }
        
        if($buynum<0){
        	$data['status']=-12;
        	$data['info']='您的挂单数量请输入正数';
        	$this->ajaxReturn($data,'JSONP');
        }

        //涨停价格限制
// 		$price_time = strtotime(date('Y-m-d',time()));
// 		$count_price['add_time'] = array('lt',$price_time);
		
// 		$price_last = M('Trade_'.$buycurrency_id)->Field('price')->where($count_price)->order('add_time desc')->find();
// 		//dump($price_last);die;
//         if ($currency['price_down']>0&&$buyprice < ( ( 1 - $currency['price_down']/100) * $price_last['price']  ) ){
//             $msg['status']=-9;
//             $msg['info']='交易价格超出了跌停价格限制';
//             $this->ajaxReturn($msg);
//         }
        
//         //涨停价格限制
//         if ($currency['price_up']>0&&$buyprice >( ( 1 + $currency['price_up']/100) * $price_last['price']  )){
//             $msg['status']=-7;
//             $msg['info']='交易价格超出了涨停价格限制';
//             $this->ajaxReturn($msg);
//         }
        
        //-----new 涨跌停-↓-----//
        $price = $this->getKlineOpen($currency['currency_id']);
		$open_price = $price;
        if ($open_price > 0 && $currency['price_down']> 0 &&$buyprice < ( ( 1 - $currency['price_down']/100) * $open_price  ) ){
        	$msg['status']=-9;
        	$msg['info']='交易价格超出了跌停价格限制';
        	$this->ajaxReturn($msg,'JSONP');
        }
        
        //涨停价格限制
        if ($open_price > 0 && $currency['price_up']>0&&$buyprice >( ( 1 + $currency['price_up']/100) * $open_price  )){
        	$msg['status']=-7;
        	$msg['info']='交易价格超出了涨停价格限制';
        	$this->ajaxReturn($msg,'JSONP');
        }
        
        //-----new 涨跌停-↑-----//
        
        if ($buyprice*$buynum<1){
            $data['status']=0;
            $data['info']='不能委托低于1元的订单';
            $this->ajaxReturn($data,'JSONP');
        }
       /*  if (!is_int($buynum)){
            $data['status']=-1;
            $data['info']='交易数量必须是整数';
            $this->ajaxReturn($data,'JSONP');
        } */
        if ($buynum<0){
            $data['status']=-2;
            $data['info']='交易数量必须是正数';
            $this->ajaxReturn($data,'JSONP');
        }
     /*    $where2['member_id']=$member_id;
        $member=M('Member')->where($where2)->find();
        if(md5($buypwd)!=$member['pwdtrade']){
            $data['status']=-3;
            $data['info']='交易密码不正确';
            $this->ajaxReturn($data,'JSONP');
        } */
        //$_SESSION['tradepwd'] = I('post.buypwd');
        if ($this->checkUserMoney($member_id,$buynum, $buyprice, 'buy', $currency)){
            $data['status']=-4;
            $data['info']='您账户余额不足';
            $this->ajaxReturn($data,'JSONP');
        }
      //  M()->query('lock tables yang_orders write, yang_currency_user write');
      
		S('huancunsuo',null);
        if(S("huancunsuo")){
        	++$l;
        	if($l>=20){
        		$data['status']=-111;
        		$data['info']="服务器交易繁忙，请稍后再试";
        		$this->ajaxReturn($data,'JSONP');exit();
        	}
        	$this->buy($_POST,$l);
        
        	 
        } 
        //设置缓存100秒
        S('huancunsuo',"1",100);
        //开启事物
        M()->startTrans();
       
        //计算买入需要的金额
        $trade_money=$buynum*$buyprice;//*(1+($currency['currency_buy_fee']/100));
      
        //操作账户
        $r[]=$this->setUserMoney($member_id,$currency['trade_currency_id'], $trade_money,'dec', 'num');
		$r[]=$this->setUserMoney($member_id,$currency['trade_currency_id'], $trade_money, 'inc','forzen_num');
        //挂单流程
        $r[]=$this->guadan($member_id,$buynum, $buyprice, 'buy', $currency);
       
       //交易流程
       $r1[]=$this->trade($member_id,$currency['currency_id'], 'buy', $buynum, $buyprice,$currency);
       foreach ($r1 as $v){
           $r[]=$v;
       }
  
 //      M()->query("UNLOCK TABLES");
       if (in_array(false, $r)){
       	
           M()->rollback();
           $msg['status']=-7;
           $msg['info']='操作未成功';
           //清除缓存
           S('huancunsuo',null);
           $this->ajaxReturn($msg,'JSONP');
       }else {
           M()->commit();
           $msg['status']=1;
           $msg['info']='操作成功';
           //清除缓存  清除已经交易完成的记录  GS 20170402
		  
           S('huancunsuo',null);
           $this->ajaxReturn($msg,'JSONP');
       }
       
    }


	/*卖出
	 * 
	 * 1.是否登录
	 * 1.5 是否开启交易
	 * 2.准备数据
	 * 3.判断数据
	 * 4.检查账户
	 * 5.操作个人账户
	 * 6.写入数据库
	 * 
	 * 
	 * 
	 */
	
	public function sell($l=1){
		$token=I('token');
		$where1['token']=$token;
		$member_id=M('token')->where($where1)->find()['uid'];
		$currency_id=I('currency_id');
		$sellprice=floatval(I('sellprice'));
		$sellnum=floatval(I('sellnum'));
		$sellpwd=I('sellpwd');
		if(!$member_id){
			$data['status']=-1;
			$data['info']='请先登录再进行此操作';
			$this->ajaxReturn($data,'JSONP');
		}
		$member=M('Member')->where('member_id='.$member_id)->find();
		if($member['status']!=3){
			$data['status']=0;
			$data['info']='您的账户未审核，不能进行交易';
			$this->ajaxReturn($data,'JSONP');
		}
		//交易时间段限制
		$currency=$this->getCurrencyByCurrencyId($currency_id);
      	//dump($currency);die;
        //交易时间段限制
        $time=strtotime(date('Y-m-d'));
		$start_time=$time+$currency['start_time_h']*3600+$currency['start_time_m']*60;
		$over_time=$time+$currency['end_time_h']*3600+$currency['end_time_m']*60;
		$start_x_time=$time+$currency['start_time_x_h']*3600+$currency['start_time_x_m']*60;
		$over_x_time=$time+$currency['end_time_x_h']*3600+$currency['end_time_x_m']*60;
		if($member_id!=184){
   		if((time()<$start_time||time()>$over_time)  &&  (time()<$start_x_time||time()>$over_x_time) ){
			$data['status']=-101;
			$data['info']='交易未开启，请在交易时间内进行交易。';
			$this->ajaxReturn($data,'JSONP');
		}
		$week = date("l",time());  //获取当前日期是周几
		if($week == 'Saturday' && $currency['is_lock_6'] == 1){
			$data['status']=-102;
			$data['info']='交易未开启，请在交易时间内进行交易。';
			$this->ajaxReturn($data,'JSONP');
		}
		if($week == 'Sunday' && $currency['is_lock_7'] == 1 ){
			$data['status']=-103;
			$data['info']='交易未开启，请在交易时间内进行交易。';
			$this->ajaxReturn($data,'JSONP');
		}
		}	
		//获取币种信息
		//$currency=$this->getCurrencyByCurrencyId($currency_id);
		//检查是否开启交易
	   if ($currency['is_lock']){
	       $msg['status']=-2;
	       $msg['info']='该币种暂时不能交易';
	       $this->ajaxReturn($msg,'JSONP');
	   }
	   
		if (empty($sellprice)||empty($sellnum)){
		    $msg['status']=-3;
		    $msg['info']='卖出价格或在数量不能为空';
		    $this->ajaxReturn($msg,'JSONP');
		}
		if($sellprice<0){
			$data['status']=-12;
			$data['info']='价格必须大于0';
			$this->ajaxReturn($data,'JSONP');
		}
		if($sellnum<0){
			$data['status']=-13;
			$data['info']='数量必须大于0';
			$this->ajaxReturn($data,'JSONP');
		}
		/* if(!is_int($sellnum)){
			$data['status']=-13;
			$data['info']='数量必须为整数';
			$this->ajaxReturn($data,'JSONP');
		} */
		if ($sellnum*$sellprice<1){
		    $data['status']=0;
		    $data['info']='不能委托低于1元的订单';
		    $this->ajaxReturn($data,'JSONP');
		}
		
		/* if (empty($sellpwd)){
		    $msg['status']=-4;
		    $msg['info']='交易密码不能为空';
		    $this->ajaxReturn($msg,'JSONP');
		} */
		/* $where2['member_id']=$member_id;
		$member=M('Member')->where($where2)->find();
		if(md5($sellpwd)!=$member['pwdtrade']){
			$data['status']=-3;
			$data['info']='交易密码不正确';
			$this->ajaxReturn($data,'JSONP');
		} */
		
		
		//涨停价格限制
// 		$price_time = strtotime(date('Y-m-d',time()));
// 		$count_price['add_time'] = array('lt',$price_time);
		
// 		$price_last = M('Trade_'.$currency_id)->Field('price')->where($count_price)->order('add_time desc')->find();
		 
// 		if ($currency['price_down']>0 && $sellprice< (( 1 - $currency['price_down']/100) * $price_last['price'] )){
// 		    $msg['status']=-9;
// 		    $msg['info']='交易价格超出了跌停价格限制';
// 		    $this->ajaxReturn($msg);
// 		}
		
// 		//涨停价格限制
// 		/* if ($currency['price_up']>0&&$sellprice>$currency['price_up']){ */
// 		if ($currency['price_up']>0&&$sellprice>(( 1 + $currency['price_up']/100) * $price_last['price']  )){
// 		    $msg['status']=-7;
// 		    $msg['info']='交易价格超出了涨停价格限制';
// 		    $this->ajaxReturn($msg);
// 		}
		$price = $this->getKlineOpen($currency['currency_id']);
		$open_price = $price;
		if ($open_price > 0 && $currency['price_down']> 0 &&$sellprice < ( ( 1 - $currency['price_down']/100) * $open_price  ) ){
			$msg['status']=-9;
			$msg['info']='交易价格超出了跌停价格限制';
			$this->ajaxReturn($msg,'JSONP');
		}
		
		//涨停价格限制
		if ($open_price > 0 && $currency['price_up']>0&&$sellprice >( ( 1 + $currency['price_up']/100) * $open_price  )){
			$msg['status']=-7;
			$msg['info']='交易价格超出了涨停价格限制';
			$this->ajaxReturn($msg,'JSONP');
		}
		//检查账户是否有钱
		if ($this->checkUserMoney($member_id,$sellnum, $sellprice, 'sell', $currency)){
		    $msg['status']=-6;
		    $msg['info']='您的账户余额不足';
		    $this->ajaxReturn($msg,'JSONP');
		}
		S('huancunsuo',null);
		if(S("huancunsuo")){
			++$l;
			if($l>=20){
				$data['status']=-111;
				$data['info']="服务器交易繁忙，请稍后再试";
				$this->ajaxReturn($data,'JSONP');exit();
			}
			$this->sell($_POST,$l);
		
		
		}
		//设置缓存100秒
		S('huancunsuo',"1",100); 
		//减可用钱 加冻结钱
		M()->startTrans();
		$r[]=$this->setUserMoney($member_id,$currency['currency_id'], $sellnum, 'dec', 'num');
		$r[]=$this->setUserMoney($member_id,$currency['currency_id'], $sellnum,'inc','forzen_num');
        //写入数据库
		$r[]=$this->guadan($member_id,$sellnum, $sellprice, 'sell', $currency);
		//成交
		$r[]=$this->trade($member_id,$currency['currency_id'], 'sell', $sellnum, $sellprice,$currency);
		
		
		if (in_array(false, $r)){
		    M()->rollback();
		    $msg['status']=-7;
		    $msg['info']='操作未成功';
		    //清除缓存
		  S('huancunsuo',null); 
		    $this->ajaxReturn($msg,'JSONP');
		}else {
		    M()->commit();
		    $msg['status']=1;
		    $msg['info']='操作成功';
		    //清除缓存
		    S('huancunsuo',null); 
		    $this->ajaxReturn($msg,'JSONP');
		}
		
	} 

	//我的成交
	public function myDeal(){
	    if (!$this->checkLogin()){
	        $this->redirect(U('Index/index','',false));
	    }
	  //获取主币种
// 		$currency=$this->getCurrencyByCurrencyId();
		$currency=$this->currency();
// 		dump($x);die;
		$this->assign('culist',$currency);
		$currencytype = I('currency');
	
		if(!empty($currencytype)){
// 			$where['currency_id'] =$currencytype;
			$c_id=$currencytype;
		}else{
			$c_id=$currency[0]['currency_id'];
		}
		M("Trade_".$c_id)->where("currency_id <> '{$c_id}'")->delete();
		$where['member_id'] = $_SESSION['member_id'];
	    
	    $count  = M('Trade_'.$c_id)->where($where)->count();// 查询满足要求的总记录数
	    $Page  = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
	    
	    //给分页传参数
	    setPageParameter($Page, array('currency'=>$currencytype));
	    
	    $show       = $Page->show();// 分页显示输出
	    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
	    $list = M('Trade_'.$c_id)->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
	    $this->assign('page',$show);// 赋值分页输出
	    $this->assign('list',$list);
	    $this->assign("c_id",$c_id);
	    $this->display();
	}
	

	
    /**
     *
     * @param int  $num 数量
     * @param float $price 价格
     * @param char $type 买buy 卖sell
     * @param $currency_id 交易币种
     */
        private function  checkUserMoney($member_id,$num,$price,$type,$currency){
        	
            //获取交易币种信息
            if ($type=='buy'){
            	
                $trade_money=$num*$price*(1+$currency['currency_buy_fee']/100);
                $currency_id=$currency['trade_currency_id'];
                $where['member_id']=$member_id;
                $money=M('Member')->where($where)->find()['rmb'];
                if ($money<$trade_money){
                	return true;
                }else{
                	return false;
                }
            }else {
                $trade_money=$num;
                
                $currency_id=$currency['currency_id'];
               
                $where['member_id']=$member_id;
                $where['currency_id']=$currency_id;
           
                $money=M('Currency_user')->where($where)->find()['num'];
                
                if ($money<$trade_money){
                	return true;
                }else{
                	return false;
                }
            }
            //和自己的账户做对比 获取账户信息
           
           
        }

    /**
     * 挂单
     * @param int  $num 数量
     * @param float $price 价格
     * @param char $type 买buy 卖sell
     * @param $currency_id 交易币种
     */
    private function guadan($member_id,$num,$price,$type,$currency){
        //获取交易币种信息
        switch ($type){
            case 'buy':
                    $fee=$currency['currency_buy_fee']/100;
                    $currency_trade_id=$currency['trade_currency_id'];
                    break;
            case 'sell':
                $fee=$currency['currency_sell_fee']/100;
                $currency_trade_id=$currency['trade_currency_id'];
                break;
        }
        $data=array(
            'member_id'=>$member_id,
            'currency_id'=>$currency['currency_id'],
            'currency_trade_id'=>$currency['trade_currency_id'],
            'price'=>$price,
            'num'=>$num,
            'trade_num'=>0,
            'fee'=>$fee,
            'type'=>$type,
        );
        if (D('Orders')->create($data)){
          $msg=D('Orders')->add();
          
        }else {
            $msg=0;
        }

        return $msg;
        
    }        

    private function trade($member_id,$currencyId,$type,$num,$price,$currency){
		
        if ($type=='buy'){
            $trade_type='sell';
        }else {
            $trade_type='buy';
        }
        
        //获取操作人一个订单
        $order=$this->getFirstOrdersByMember($member_id,$type ,$currencyId);
        //获取对应交易的一个订单
        $trade_order=$this->getOneOrders($trade_type, $currencyId,$price);
       //如果没有相匹配的订单，直接返回
        if (empty($trade_order)){
            $r[]=true;
            return $r;
        }
        //如果有就处理订单
        $trade_num=min($num,$trade_order['num']-$trade_order['trade_num']);
        //增加本订单的已经交易的数量
        $r[]=M('Orders')->where("orders_id={$order['orders_id']}")->setInc('trade_num',$trade_num);
        $r[]=M('Orders')->where("orders_id={$order['orders_id']}")->setField('trade_time',time());
        //增加trade订单的已经交易的数量
        $r[]=M('Orders')->where("orders_id={$trade_order['orders_id']}")->setInc('trade_num',$trade_num);
        $r[]=M('Orders')->where("orders_id={$trade_order['orders_id']}")->setField('trade_time',time());
        
        //更新一下订单状态
        $r[]=M('Orders')->where("trade_num>0 and status=0")->setField('status',1);
        $r[]=M('Orders')->where("num=trade_num")->delete();  //直接删除订单信息  GS 20170402
        

        //处理资金
        switch ($type){
           
            case 'buy':
                $trade_price=min($order['price'],$trade_order['price']);
                $trade_order_money= $trade_num*$trade_price*(1-$trade_order['fee']);
                $order_money= $trade_num*$trade_price;//*(1+$order['fee']);
                $r[]=$this->setUserMoney($member_id,$order['currency_id'], $trade_num*(1-$order['fee']), 'inc', 'num');
                $r[]=$this->setUserMoney($member_id,$order['currency_trade_id'], $order_money+ $trade_num*($order['price']-$trade_price), 'dec', 'forzen_num');
                
                $r[]=$this->setUserMoney($trade_order['member_id'],$trade_order['currency_id'],  $trade_num, 'dec', 'forzen_num');
                $r[]=$this->setUserMoney($trade_order['member_id'],$trade_order['currency_trade_id'], $trade_order_money, 'inc', 'num');
                
                //返还多扣除的部分
               $r[]=$this->setUserMoney($member_id,$order['currency_trade_id'], $trade_num*($order['price']-$trade_price), 'inc', 'num');
              	//合并SQL语句  RZM 20170403
             //  $r[]=$this->setUserMoney($this->member['member_id'],$order['currency_trade_id'], $trade_num*($order['price']-$trade_price), 'dec', 'forzen_num');
                //手续费
                $r[]=$this->addFinance($order['member_id'], 11, '交易手续费',$trade_num*$order['fee'], 2, $order['currency_id']);
                $r[]=$this->addFinance($trade_order['member_id'], 11, '交易手续费',$trade_num*$trade_price*$trade_order['fee'], 2, $order['currency_trade_id']);
                break;
            case 'sell':
                $trade_price=max($order['price'],$trade_order['price']);
                $order_money= $trade_num*$trade_price*(1-$order['fee']);
                $trade_order_money= $trade_num*$trade_price;//*(1+$trade_order['fee']);
              
                
                $r[]=$this->setUserMoney($member_id,$order['currency_id'], $trade_num, 'dec', 'forzen_num');
                $r[]=$this->setUserMoney($member_id,$order['currency_trade_id'], $order_money, 'inc', 'num');
                 
                $r[]=$this->setUserMoney($trade_order['member_id'],$trade_order['currency_id'], $trade_num*(1-$trade_order['fee']), 'inc', 'num');
                $r[]=$this->setUserMoney($trade_order['member_id'],$trade_order['currency_trade_id'],$trade_order_money, 'dec', 'forzen_num');
                //手续费  判断如果手续费等于0 不写入日志表
                if($trade_num*$trade_price*$order['fee'] != 0){
                $r[]=$this->addFinance($order['member_id'], 11, '交易手续费',$trade_num*$trade_price*$order['fee'], 2, $order['currency_trade_id']);
                }
                if($trade_num*$trade_order['fee'] != 0){
                $r[]=$this->addFinance($trade_order['member_id'], 11, '交易手续费',$trade_num*$trade_order['fee'], 2, $order['currency_id']);
                }
                break;
        }
        //修正最终成交的价格   记录已经删除不需要再修正  RZM 20170403
       // $r[]=M('Orders')->where("num=trade_num and orders_id={$order['orders_id']}")->setField('price',$trade_price);
        //$r[]=M('Orders')->where("num=trade_num and orders_id={$trade_order['orders_id']}")->setField('price',$trade_price);
        
       $TLogic = new TradeLogic($currencyId);
        //写入成交表
//         $r[]=$this->addTrade($order['member_id'], $order['currency_id'], $order['currency_trade_id'],$trade_price, $trade_num, $order['type'],$order['fee']);
        $r[]=$TLogic->addTradeOne($order['member_id'], $order['currency_id'], $order['currency_trade_id'],$trade_price, $trade_num, $order['type'],$order['fee']);
        $r[]=$this->addReward($order['member_id'],$currency,$trade_price*$trade_num*$order['fee']);
//         $r[]=$this->addTrade($trade_order['member_id'], $trade_order['currency_id'], $trade_order['currency_trade_id'], $trade_price, $trade_num, $trade_order['type'],$trade_order['fee']);       
    	$r[]=$TLogic->addTradeOne($trade_order['member_id'],$trade_order['currency_id'], $trade_order['currency_trade_id'], $trade_price, $trade_num, $trade_order['type'],$trade_order['fee']);       
        $r[]=$this->addReward($order['member_id'],$currency,$trade_price*$trade_num*$trade_order['fee']);
		/************************************这里用于写入交易数据文件*******************************************************/
		//计算存储  该币种 最新价格，24小时涨跌，7D涨跌，24小时成交量，24小时成交额，最低价，最高价，总市值
		
		/*******************************************************************************************/
        
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_1m');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_3m');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_5m');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_15m');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_30m');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_1h');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_2h');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_4h');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_6h');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_12h');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_1d');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_7d');
		$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_1M');
		//$this->setKlineData($currencyId,$trade_price,$trade_num,'kline_1Y');
	    $num =$num- $trade_num;
	   //dump($num);
        if ($num>0){
            //递归
        	
           $r[]= $this->trade($member_id,$currencyId, $type, $num, $price,$currency);
        }
        
        $this->getCurrencyMessageById($currencyId);
       
        return $r;
        
    }
    protected function setKlineData($sharesId,$price,$num,$get_data = 'kline_1m'){
    	$price = floatval($price);
    	$num = intval($num);
    	$url = __APP__.'KlineData/';
    	switch ($get_data){
    		case 'kline_1m':
    			$time = $this->_getTime(1)*1000;;//strtotime(date('Y-m-d H:i',time()))*1000;
    			$all  = 60*1000;
    			$file_name = $url.'KLineData_kline_0_'.$sharesId.'.js';
    			break;
    		case 'kline_3m':
    			$time = $this->_getTime(3)*1000;
    			$all  = 60*3*1000;
    			$file_name = $url.'KLineData_kline_7_'.$sharesId.'.js';
    			break;
    		case 'kline_5m':
    			$time = $this->_getTime(5)*1000;
    			$all  = 60*5*1000;
    			$file_name = $url.'KLineData_kline_1_'.$sharesId.'.js';
    			break;
    		case 'kline_15m':
    			$time = $this->_getTime(15)*1000;
    			$all  = 60*15*1000;
    			$file_name = $url.'KLineData_kline_2_'.$sharesId.'.js';
    			break;
    		case 'kline_30m':
    			$time = $this->_getTime(30)*1000;
    			$all  = 60*30*1000;
    			$file_name = $url.'KLineData_kline_9_'.$sharesId.'.js';
    			break;
    		case 'kline_1h':
    			$time = $this->_getTime(60)*1000;
    			$all  = 60*60*1000;
    			$file_name = $url.'KLineData_kline_10_'.$sharesId.'.js';
    			break;
    		case 'kline_2h':
    			$time = $this->_getTime(60*2)*1000;
    			$all  = 120*60*1000;
    			$file_name = $url.'KLineData_kline_11_'.$sharesId.'.js';
    			break;
    		case 'kline_4h':
    			$time = $this->_getTime(60*4)*1000;
    			$all  = 240*60*1000;
    			$file_name = $url.'KLineData_kline_12_'.$sharesId.'.js';
    			break;
    		case 'kline_6h':
    			$time = $this->_getTime(60*6)*1000;
    			$all  = 360*60*1000;
    			$file_name = $url.'KLineData_kline_13_'.$sharesId.'.js';
    			break;
    		case 'kline_12h':
    			$time = $this->_getTime(60*12)*1000;
    			$all  = 720*60*1000;
    			$file_name = $url.'KLineData_kline_14_'.$sharesId.'.js';
    			break;
    		case 'kline_1d':
    			$time = $this->_getTime(60*24)*1000;
    			$all  = 1440*60*1000;
    			$file_name = $url.'KLineData_kline_3_'.$sharesId.'.js';
    			break;
    		case 'kline_7d':
    			$time = $this->_getTime(60*24*7)*1000;
    			$all  = 7*1440*60*1000;
    			$file_name = $url.'KLineData_kline_4_'.$sharesId.'.js';
    			break;
    		case 'kline_1M':
    			$time = mktime(0,0,0,date('m'),1,date('Y'))*1000;
    			$all  = 30*1440*60*1000;
    			$file_name = $url.'KLineData_kline_15_'.$sharesId.'.js';
    			break;
    		case 'kline_1Y':
    			$time = strtotime(date('Y',time()).'-01-01 00:00:00')*1000;
    			$all  = 24*60*60*1000*365;
    			$file_name = $url.'KLineData_kline_16_'.$sharesId.'.js';
    			break; 
    				
    	}
    	$file_get  = file_get_contents($file_name);
    	$file_ex   = file_exists($file_name);
    	if($file_ex == false || $file_get == ''){
    		$data[] = [
    		$time, //时间
    		$price,//开
    		$price,//高
    		$price,//底
    		$price,//收
    		$num,//量
    		];
    		file_put_contents($file_name, json_encode($data));
    	}else{
    		$data = file_get_contents($file_name);
    		$data = json_decode($data);
    		$count = count($data);
    		if($count>800){
    			$del = $data;
    			$data = array_slice($del,300);
    		}
    		$end_arr = end($data);
    		if($end_arr[0] == $time){
    			$arr[] = $end_arr[0];
    			$arr[] = $end_arr[1];
    			$arr[] = max($end_arr[2],$price);
    			$arr[] = min($end_arr[3],$price);
    			$arr[] = $price;
    			$arr[] = $end_arr[5]+$num;
    			array_pop($data);
    			array_push($data, $arr);
    		}else{
//     			$o = (int)(($time - $end_arr[0])/$all);
//     			if($o > 1 ){
//     				for($i=1;$i<$o;$i++){
//     					$arr[] = $end_arr[0]+($i*$all);
//     					$arr[] = $end_arr[4];
//     					$arr[] = $end_arr[4];
//     					$arr[] = $end_arr[4];
//     					$arr[] = $end_arr[4];
//     					$arr[] = 0;
//     					array_push($data, $arr);
//     					unset($arr);
//     				}
//     			}
    			$arr[] = $time;
    			$arr[] = $price;
    			$arr[] = $price;
    			$arr[] = $price;
    			$arr[] = $price;
    			$arr[] = $num;
    			array_push($data, $arr);
    		}
    	}
    	file_put_contents($file_name, json_encode($data));
    	return json_encode($data);
    }
    
    private function _getTime($type){
    	return time()-time()%($type*60);
    }
    /**
     * 返回一条挂单记录
     * @param int $currencyId 币种id
     * @param float $price 交易价格
     * @return array 挂单记录
     */
    private function getOneOrders($type,$currencyId,$price){
        switch ($type){
            case 'buy':$gl='egt';$order='price desc'; break;
            case 'sell':$gl='elt'; $order='price asc';break;
        }
        $where['currency_id']=$currencyId;
        $where['type']=$type;
        $where['price']=array($gl,$price);
        $where['status']=array('in',array(0,1));
        return M('Orders')->where($where)->order('add_time desc')->order($order)->find();
    }
    /**
     * 返回用户第一条未成交的挂单
     * @param int $memberId 用户id
     * @param int $currencyId 币种id
     * @return array 挂单记录
     */
    private function getFirstOrdersByMember($memberId,$type,$currencyId){
        $where['member_id']=$memberId;
        $where['currency_id']=$currencyId;
        $where['type']=$type;
        $where['status']=array('in',array(0,1));
        return M('Orders')->where($where)->order('add_time desc')->find();
    }
    /**
     *  返回指定价格排序的订单
     * @param char $type  buy sell
     * @param float $price   交易价格
     * @param char $order 排序方式
     */
    private function getOrdersByPrice($currencyId,$type,$price,$order){
        switch ($type){
            case 'buy': $gl='elt';break;
            case 'sell': $gl='egt';break;
        }
        $where['currency_id']=$currencyId;
        $where['price']=array($gl,$price);
        $where['status']=array('in',array(0,1));
        return  M('Orders')->where($where)->order("price  $order")->select();
    }


//     /**
//      * 增加交易记录
//      * @param unknown $member_id
//      * @param unknown $currency_id
//      * @param unknown $currency_trade_id
//      * @param unknown $price
//      * @param unknown $num
//      * @param unknown $type
//      * @return boolean
//      */
//     private function  addTrade($member_id,$currency_id,$currency_trade_id,$price,$num,$type,$fee){
//         $fee=$price*$num*$fee;
//         $this->dividend($price*$num,$member_id);
//         $data=array(
//             'member_id'=>$member_id,
//             'currency_id'=>$currency_id,
//             'currency_trade_id'=>$currency_trade_id,
//             'price'=>$price,
//             'num'=>$num,
//             'fee'=>$fee,
//             'money'=>$price*$num,
//             'type'=>$type,
//         );
//         if (D('Trade')->create($data)){
//             if (D('Trade')->add()){
// 				//对上级进行奖励
// 				$this->addReward($member_id,$currency_id,$fee);
//                 return true;
//             }else {
//                 return false;
//             }
//         }else {
//             return false;
//         }
//     }

	/**
	*给上级的交易手续费的百分比的奖励
	*2016.12.26   GS
	*/
	private function addReward($member_id,$currency,$fee){
		if(empty($fee)){
			return true;
		}
		if(empty($currency['currency_fee_reward'])){
			return true;
		}
		$user_info = M('Member')->field("pid")->where("member_id={$member_id}")->find();
		$pid = $user_info['pid'];
		//判断是否有上级推荐人
		if(!empty($pid)){
// 			$Currency = M('Currency')->where("currency_id={$currency_id}")->find();
			$currency_fee_reward = $currency['currency_fee_reward'];
			$reward_money = intval(($fee * $currency_fee_reward)*100) / 10000;
			//dump($fee);
			//dump($reward_money);die;
			//为上级进行奖励发放
			$re = M('Member')->where("`member_id`={$pid}")->setInc('rmb',$reward_money);
			if($re){
				//加入日志
				$uname = substr($user_info['email'],0,-2).'**';
				 $r[]=$this->addFinance($pid, 24, $uname.'产生的交易奖励',$reward_money, 1, 0);
			}
		}
	}
	
}